<template>
  <div class="host-management">
    <div class="card">
      <div class="card-header-wrapper">
        <div class="card-header flex-between">
          <div class="header-title">
            <span class="title-text">主机列表</span>
          </div>
          <div class="header-actions">
            <button @click="exportToExcel" class="btn-action btn-export" title="导出所有主机信息到Excel">
              <span class="btn-icon">📊</span>
              <span class="btn-text">导出Excel</span>
            </button>
            <button @click="syncAllHosts" class="btn-action btn-sync" title="同步所有主机状态">
              <span class="sync-icon" :class="{ 'syncing': isSyncing }">⟳</span>
              <span class="btn-text">同步主机</span>
            </button>
            <div class="sync-controls-group">
              <label class="sync-toggle-inline">
                <input type="checkbox" v-model="autoSyncEnabled" @change="toggleAutoSync" />
                <span class="toggle-text">自动同步</span>
              </label>
              <select v-model="syncInterval" @change="updateSyncInterval" class="sync-interval-select-inline">
                <option :value="5">5秒</option>
                <option :value="10">10秒</option>
                <option :value="15">15秒</option>
                <option :value="20">20秒</option>
                <option :value="25">25秒</option>
                <option :value="30">30秒</option>
                <option :value="35">35秒</option>
                <option :value="40">40秒</option>
                <option :value="45">45秒</option>
                <option :value="50">50秒</option>
                <option :value="55">55秒</option>
                <option :value="60">60秒</option>
              </select>
              <span class="sync-indicator-inline" :class="{ 'active': autoSyncEnabled }" title="同步状态指示器">
                <span class="triangle">▶</span>
              </span>
            </div>
            <button @click="showAddModal = true" class="btn-action btn-add">
              <span class="btn-icon">+</span>
              <span class="btn-text">添加主机</span>
            </button>
          </div>
        </div>
      </div>

      <!-- 批量操作工具栏 -->
      <div v-if="selectedHosts.length > 0" class="bulk-actions-bar">
        <span class="selected-count">已选择 {{ selectedHosts.length }} 台主机</span>
        <div class="action-buttons">
          <button @click="bulkStopHosts" class="btn btn-danger btn-sm">
            ■ 批量关机
          </button>
          <button @click="clearSelection" class="btn btn-secondary btn-sm">
            ✕ 取消选择
          </button>
        </div>
      </div>

      <div class="filters mb-2">
        <input 
          v-model="searchQuery" 
          type="text" 
          placeholder="搜索主机名或IP..."
          class="search-input"
        />
      </div>

      <div v-if="loading" class="text-center p-2">
        <div class="loading"></div>
      </div>

      <div class="table-wrapper" v-else>
        <div class="scroll-hint">← 左右滑动查看更多列 →</div>
        <table>
        <thead>
          <tr>
            <th style="width: 40px;">
              <input type="checkbox" @change="toggleSelectAll" :checked="isAllSelected" />
            </th>
            <th>主机名称</th>
            <th>IP地址</th>
            <th>端口</th>
            <th>用户名</th>
            <th>认证方式</th>
            <th>状态</th>
            <th>系统类型</th>
            <th>系统版本</th>
            <th>CPU核心</th>
            <th>CPU架构</th>
            <th>内存</th>
            <th>磁盘</th>
            <th>公网IP</th>
            <th>内网IP</th>
            <th>项目</th>
            <th>环境</th>
            <th>描述</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="host in filteredHosts" :key="host.id" :class="{ 'selected-row': isHostSelected(host.id) }">
            <td>
              <input type="checkbox" :checked="isHostSelected(host.id)" @change="toggleHostSelection(host.id)" />
            </td>
            <td>{{ host.name }}</td>
            <td>{{ host.ip }}</td>
            <td>{{ host.port }}</td>
            <td>{{ host.username }}</td>
            <td>{{ host.auth_type === 'password' ? '密码' : '密钥' }}</td>
            <td>
              <span 
                :class="['badge', getStatusClass(host.status)]"
              >
                {{ getStatusText(host.status) }}
              </span>
            </td>
            <td>
              <span :class="['os-type-badge', host.os_type ? '' : 'no-data']">
                {{ host.os_type || '-' }}
              </span>
            </td>
            <td>
              <span class="text-small">{{ host.os_version || '-' }}</span>
            </td>
            <td>
              <span class="cpu-info">{{ host.cpu_cores ? host.cpu_cores + '核' : '-' }}</span>
            </td>
            <td>
              <span class="arch-badge">{{ host.cpu_arch || '-' }}</span>
            </td>
            <td>
              <div v-if="host.memory_total && host.memory_used" class="resource-progress">
                <div class="progress-bar">
                  <div class="progress-fill memory" :style="{ width: getMemoryPercent(host) + '%' }"></div>
                </div>
                <div class="progress-text">{{ getMemoryText(host) }}</div>
              </div>
              <span v-else class="memory-info">{{ host.memory_info || '-' }}</span>
            </td>
            <td>
              <div v-if="host.disk_total && host.disk_used" class="resource-progress">
                <div class="progress-bar">
                  <div class="progress-fill disk" :style="{ width: getDiskPercent(host) + '%' }"></div>
                </div>
                <div class="progress-text">{{ getDiskText(host) }}</div>
              </div>
              <span v-else class="disk-info">{{ host.disk_info || '-' }}</span>
            </td>
            <td>
              <span class="ip-badge public">{{ host.public_ip || '-' }}</span>
            </td>
            <td>
              <span class="ip-badge private">{{ host.private_ip || '-' }}</span>
            </td>
            <td>{{ host.project_name || '-' }}</td>
            <td>{{ getHostEnvTypeName(host) }}</td>
            <td>
              <span 
                class="description-preview" 
                :title="host.description ? '点击查看完整描述' : '点击查看（暂无描述）'"
                @click="showDescriptionDetail(host)">
                📄 {{ getDescriptionPreview(host.description) }}
              </span>
            </td>
            <td>
              <div class="flex gap-1">
                <button 
                  v-if="host.status === 'online'"
                  @click="toggleHostPower(host)" 
                  class="btn btn-sm btn-warning" 
                  title="关机/重启主机"
                  style="padding: 4px 8px; font-size: 10px;">
                  ■
                </button>
                <button @click="openTerminal(host)" class="btn btn-info btn-sm" style="padding: 4px 8px; font-size: 10px;">终端</button>
                <button @click="editHost(host)" class="btn btn-sm" style="padding: 4px 8px; font-size: 10px;">编辑</button>
                <button @click="deleteHost(host.id)" class="btn btn-danger btn-sm" style="padding: 4px 8px; font-size: 10px;">删除</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
      </div>
    </div>

    <!-- Terminal Section -->
    <div v-if="activeTerminals.length > 0" class="terminals-section mt-2">
      <div v-for="term in activeTerminals" :key="term.id" class="terminal-wrapper">
        <Terminal 
          :host-id="term.id" 
          :host-name="term.name"
          @close="closeTerminal(term.id)"
        />
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal || showEditModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ showEditModal ? '编辑主机' : '添加主机' }}</h2>
          <button @click="closeModal" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveHost">
            <div class="form-group">
              <label>主机名称 *</label>
              <input v-model="formData.name" type="text" required />
            </div>
            <div class="form-group">
              <label>IP地址 *</label>
              <input v-model="formData.ip" type="text" required />
            </div>
            <div class="form-group">
              <label>SSH端口</label>
              <input v-model.number="formData.port" type="number" />
            </div>
            <div class="form-group">
              <label>SSH用户名 *</label>
              <input v-model="formData.username" type="text" required />
            </div>
            <div class="form-group">
              <label>认证方式</label>
              <select v-model="formData.auth_type">
                <option value="password">密码认证</option>
                <option value="key">密钥认证</option>
              </select>
            </div>
            <div v-if="formData.auth_type === 'password'" class="form-group">
              <label>SSH密码 *</label>
              <input v-model="formData.password" type="password" required />
            </div>
            <div v-else class="form-group">
              <label>SSH私钥 *</label>
              <textarea v-model="formData.ssh_key" rows="5" required></textarea>
            </div>
            
            <div class="form-group">
              <label>主机描述</label>
              <textarea v-model="formData.description" rows="3" placeholder="输入主机的用途、特点等描述信息..."></textarea>
            </div>
            
            <!-- 测试SSH连接按钮 -->
            <div v-if="showEditModal" class="form-group">
              <button 
                type="button" 
                @click="testSSH" 
                class="btn btn-test-ssh"
                :disabled="isTestingSSH">
                {{ isTestingSSH ? '测试中...' : '🔌 测试SSH连接' }}
              </button>
              <small style="color: #888; font-size: 12px; display: block; margin-top: 8px;">
                建议先测试SSH连接，确保配置正确后再获取MAC地址
              </small>
            </div>
            
            <div class="form-group">
              <label>MAC地址 (用于远程开机)</label>
              <div class="flex gap-1" style="align-items: flex-start;">
                <input v-model="formData.mac_address" type="text" placeholder="00:11:22:33:44:55" style="flex: 1;" />
                <button 
                  type="button" 
                  @click="autoGetMac" 
                  class="btn btn-sm btn-auto-get"
                  :disabled="isGettingMac"
                  title="自动获取MAC地址">
                  {{ isGettingMac ? '获取中...' : '🔄 自动获取' }}
                </button>
              </div>
              <small style="color: #888; font-size: 12px;">
                格式: 00:11:22:33:44:55 (用于Wake-on-LAN开机，需要SSH能连接才能自动获取)
              </small>
            </div>
            
            <div class="form-group">
              <label>项目</label>
              <select v-model="formData.project">
                <option value="">请选择项目</option>
                <option v-for="proj in projects" :key="proj.id" :value="proj.id">
                  {{ proj.name }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>环境</label>
              <div class="flex gap-1">
                <select v-model="formData.environment" style="flex: 1;">
                  <option value="">请选择环境</option>
                  <option v-for="env in environments" :key="env.id" :value="env.id">
                    {{ env.name }} ({{ getEnvTypeName(env.env_type) }})
                  </option>
                </select>
                <button type="button" @click="showAddEnvModal = true" class="btn btn-sm" title="添加新环境">+</button>
              </div>
            </div>
            <div class="form-group">
              <label>主机组</label>
              <select v-model="formData.host_group">
                <option value="">请选择主机组</option>
                <option v-for="group in hostGroups" :key="group.id" :value="group.id">
                  {{ group.name }}
                </option>
              </select>
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">保存</button>
              <button type="button" @click="closeModal" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 添加环境快捷弹窗 -->
    <div v-if="showAddEnvModal" class="modal" @click.self="showAddEnvModal = false">
      <div class="modal-content modal-sm">
        <div class="modal-header">
          <h2>快速添加环境</h2>
          <button @click="showAddEnvModal = false" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveNewEnvironment">
            <div class="form-group">
              <label>环境名称 *</label>
              <input v-model="newEnvData.name" type="text" required />
            </div>
            <div class="form-group">
              <label>环境类型 *</label>
              <select v-model="newEnvData.env_type" required>
                <option value="">请选择</option>
                <option value="dev">开发环境</option>
                <option value="test">测试环境</option>
                <option value="staging">预发布环境</option>
                <option value="prod">生产环境</option>
              </select>
            </div>
            <div class="form-group">
              <label>环境描述</label>
              <textarea v-model="newEnvData.description" rows="2"></textarea>
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">创建</button>
              <button type="button" @click="showAddEnvModal = false" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 描述详情对话框 -->
    <div v-if="showDescriptionModal" class="modal" @click.self="showDescriptionModal = false">
      <div class="modal-content modal-sm">
        <div class="modal-header">
          <h2>📝 主机描述详情</h2>
          <button @click="showDescriptionModal = false" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <div class="description-detail">
            <div class="host-info-row">
              <span class="label">主机名称:</span>
              <span class="value">{{ currentHost?.name }}</span>
            </div>
            <div class="host-info-row">
              <span class="label">IP地址:</span>
              <span class="value">{{ currentHost?.ip }}</span>
            </div>
            <div class="description-content">
              <div class="label">描述内容:</div>
              <div class="value description-text" :class="{ 'empty-description': !currentHost?.description }">
                {{ currentHost?.description || '暂无描述信息，点击下方"编辑主机"按钮可以添加描述' }}
              </div>
            </div>
          </div>
          <div class="flex gap-1 mt-2">
            <button @click="showDescriptionModal = false" class="btn">关闭</button>
            <button @click="editHostFromDetail" class="btn btn-primary">编辑主机</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onBeforeUnmount } from 'vue'
import api from '../services/api'
import Terminal from '../components/Terminal.vue'
import * as XLSX from 'xlsx'
import dialog from '../utils/dialog'

const hosts = ref([])
const loading = ref(false)
const searchQuery = ref('')
const showAddModal = ref(false)
const showEditModal = ref(false)
const showDescriptionModal = ref(false)
const currentHost = ref(null)
const activeTerminals = ref([])
const isGettingMac = ref(false)
const isTestingSSH = ref(false)

const projects = ref([])
const environments = ref([])
const hostGroups = ref([])
const showAddEnvModal = ref(false)
const newEnvData = ref({
  name: '',
  env_type: '',
  description: ''
})

const formData = ref({
  name: '',
  ip: '',
  mac_address: '',
  port: 22,
  username: '',
  auth_type: 'password',
  password: '',
  ssh_key: '',
  project: '',
  environment: '',
  host_group: '',
  description: ''
})

// 批量操作相关
const selectedHosts = ref([])
const isSyncing = ref(false)
const autoSyncEnabled = ref(false)
const syncInterval = ref(30) // 默认30秒
let syncTimer = null

const filteredHosts = computed(() => {
  if (!searchQuery.value) return hosts.value
  const query = searchQuery.value.toLowerCase()
  return hosts.value.filter(host => 
    host.name.toLowerCase().includes(query) ||
    host.ip.toLowerCase().includes(query)
  )
})

const isAllSelected = computed(() => {
  return filteredHosts.value.length > 0 && 
         selectedHosts.value.length === filteredHosts.value.length
})

onMounted(() => {
  fetchHosts()
  fetchProjects()
  fetchEnvironments()
  fetchHostGroups()
})

const fetchHosts = async () => {
  loading.value = true
  try {
    const response = await api.getHosts()
    hosts.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch hosts:', error)
  } finally {
    loading.value = false
  }
}

const fetchProjects = async () => {
  try {
    const response = await api.getProjects()
    projects.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch projects:', error)
  }
}

const fetchEnvironments = async () => {
  try {
    const response = await api.getEnvironments()
    environments.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch environments:', error)
  }
}

const fetchHostGroups = async () => {
  try {
    const response = await api.getHostGroups()
    hostGroups.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch host groups:', error)
  }
}

const openTerminal = (host) => {
  if (!activeTerminals.value.find(t => t.id === host.id)) {
    activeTerminals.value.push(host)
  }
}

const closeTerminal = (hostId) => {
  activeTerminals.value = activeTerminals.value.filter(t => t.id !== hostId)
}

const editHost = (host) => {
  formData.value = { 
    ...host,
    project: host.project || '',
    environment: host.environment || '',
    host_group: host.host_group || ''
  }
  showEditModal.value = true
}

// 测试SSH连接
const testSSH = async () => {
  if (!formData.value.id) {
    alert('请先保存主机信息后再测试连接')
    return
  }
  
  isTestingSSH.value = true
  try {
    const result = await api.testSSHConnection(formData.value.id)
    alert(`✅ ${result.message}\n\n主机信息:\n名称: ${result.host_info.name}\nIP: ${result.host_info.ip}\n端口: ${result.host_info.port}\n用户: ${result.host_info.username}\n\nSSH连接正常，可以获取MAC地址了！`)
  } catch (error) {
    console.error('SSH连接测试失败:', error)
    const errorData = error.response?.data || {}
    const errorMsg = errorData.error || error.message
    const details = errorData.details || ''
    alert(`❌ SSH连接测试失败: ${errorMsg}\n\n详情: ${details}\n\n请检查:\n1. IP地址是否正确\n2. 端口是否正确（默认22）\n3. 用户名密码是否正确\n4. 主机是否在线\n5. 网络是否可达`)
  } finally {
    isTestingSSH.value = false
  }
}

// 自动获取MAC地址
const autoGetMac = async () => {
  // 验证必需字段
  if (!formData.value.ip) {
    alert('❌ 请先填写IP地址')
    return
  }
  if (!formData.value.username) {
    alert('❌ 请先填写SSH用户名')
    return
  }
  if (formData.value.auth_type === 'password' && !formData.value.password) {
    alert('❌ 密码认证需要填写密码')
    return
  }
  if (formData.value.auth_type === 'key' && !formData.value.ssh_key) {
    alert('❌ 密钥认证需要填写SSH密钥')
    return
  }
  
  isGettingMac.value = true
  try {
    const result = await api.getMacAddress({
      ip: formData.value.ip,
      port: formData.value.port || 22,
      username: formData.value.username,
      auth_type: formData.value.auth_type,
      password: formData.value.password,
      ssh_key: formData.value.ssh_key
    })
    formData.value.mac_address = result.mac_address
    alert(`✅ MAC地址获取成功！\n\nMAC地址: ${result.mac_address}\n\n已自动填写到表单中`)
  } catch (error) {
    console.error('获取MAC地址失败:', error)
    const errorMsg = error.response?.data?.error || error.message
    alert(`❌ 获取MAC地址失败: ${errorMsg}\n\n请检查:\n1. IP地址是否正确\n2. SSH端口是否正确\n3. 用户名和密码/密钥是否正确\n4. 主机是否在线\n5. 网络是否可达`)
  } finally {
    isGettingMac.value = false
  }
}

const saveHost = async () => {
  try {
    // 数据验证
    if (!formData.value.name || !formData.value.name.trim()) {
      alert('❌ 请输入主机名称')
      return
    }
    if (!formData.value.ip || !formData.value.ip.trim()) {
      alert('❌ 请输入IP地址')
      return
    }
    if (!formData.value.username || !formData.value.username.trim()) {
      alert('❌ 请输入SSH用户名')
      return
    }
    
    // 认证方式验证
    if (formData.value.auth_type === 'password') {
      if (!formData.value.password && !showEditModal.value) {
        alert('❌ 密码认证需要输入密码')
        return
      }
    } else if (formData.value.auth_type === 'key') {
      if (!formData.value.ssh_key && !showEditModal.value) {
        alert('❌ 密钥认证需要输入SSH密钥')
        return
      }
    }
    
    // 清理数据 - 空字符串字段保持空字符串，外键字段转为null
    const data = { ...formData.value }
    const foreignKeyFields = ['project', 'environment', 'host_group', 'ipmi_address']
    Object.keys(data).forEach(key => {
      if (data[key] === '' && foreignKeyFields.includes(key)) {
        data[key] = null
      }
    })
    
    // 清理不需要的认证字段
    if (data.auth_type === 'password') {
      delete data.ssh_key
    } else if (data.auth_type === 'key') {
      delete data.password
    }
    
    if (showEditModal.value) {
      await api.updateHost(data.id, data)
      console.log('主机信息更新成功')
    } else {
      await api.createHost(data)
      console.log('主机添加成功')
    }
    await fetchHosts()
    closeModal()
  } catch (error) {
    console.error('保存失败:', error)
    let errorMsg = '保存失败'
    
    if (error.response?.data) {
      const data = error.response.data
      if (typeof data === 'object') {
        // 处理字段错误
        const errors = []
        for (const [field, messages] of Object.entries(data)) {
          if (Array.isArray(messages)) {
            errors.push(`${field}: ${messages.join(', ')}`)
          } else if (typeof messages === 'string') {
            errors.push(`${field}: ${messages}`)
          }
        }
        if (errors.length > 0) {
          errorMsg = errors.join('\n')
        }
      } else if (data.detail) {
        errorMsg = data.detail
      } else if (data.error) {
        errorMsg = data.error
      }
    } else if (error.message) {
      errorMsg = error.message
    }
    
    alert('❌ ' + errorMsg)
  }
}

const deleteHost = async (id) => {
  const confirmed = await dialog.confirm('确定要删除这个主机吗？\n\n此操作不可撤销，请谨慎操作', '确认删除')
  if (!confirmed) return
  
  try {
    await api.deleteHost(id)
    await fetchHosts()
    console.log('主机删除成功')
  } catch (error) {
    console.error('Failed to delete host:', error)
    // 错误信息已在控制台显示
  }
}

// 立即巡检单个主机
const inspectHost = async (host) => {
  if (!confirm(`确定要对主机 ${host.name} (${host.ip}) 执行巡检吗？`)) return
  
  try {
    const response = await api.inspectHosts([host.id])
    
    // 显示巡检结果
    if (response && response.length > 0) {
      const result = response[0]
      let message = `主机: ${result.host_name}\n状态: ${result.status === 'online' ? '在线' : '离线'}\n`
      
      if (result.status === 'online') {
        message += `\nCPU使用率: ${result.cpu?.usage_percent?.toFixed(2)}%`
        message += `\n内存使用率: ${result.memory?.usage_percent?.toFixed(2)}%`
        message += `\n磁盘使用率: ${result.disk?.usage_percent?.toFixed(2)}%`
        
        if (result.warnings && result.warnings.length > 0) {
          message += `\n\n⚠️ 警告:\n${result.warnings.join('\n')}`
        }
        
        if (result.auto_resolved > 0) {
          message += `\n\n✅ 自动解决了 ${result.auto_resolved} 条警告`
        }
        
        alert('✅ 巡检完成!\n\n' + message)
      } else {
        message += `\n错误: ${result.error || '无法连接'}`
        alert('❌ 巡检失败!\n\n' + message)
      }
    }
  } catch (error) {
    console.error('巡检失败:', error)
    alert('巡检失败: ' + (error.response?.data?.error || error.message))
  }
}

// 保存新环境
const saveNewEnvironment = async () => {
  try {
    const response = await api.createEnvironment(newEnvData.value)
    await fetchEnvironments()
    // 自动选择新创建的环境
    formData.value.environment = response.id
    showAddEnvModal.value = false
    // 清空表单
    newEnvData.value = {
      name: '',
      env_type: '',
      description: ''
    }
    alert('环境创建成功！')
  } catch (error) {
    console.error('Failed to create environment:', error)
    alert('创建环境失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 获取环境类型名称
const getEnvTypeName = (type) => {
  const types = {
    'dev': '开发',
    'test': '测试',
    'staging': '预发布',
    'prod': '生产'
  }
  return types[type] || type
}

// 获取主机的环境类型名称
const getHostEnvTypeName = (host) => {
  if (!host.environment) return '-'
  
  // 从environments列表中找到对应的环境
  const env = environments.value.find(e => e.id === host.environment)
  if (env && env.env_type) {
    const typeNames = {
      'dev': '开发环境',
      'test': '测试环境',
      'staging': '预发布环境',
      'prod': '生产环境'
    }
    return typeNames[env.env_type] || env.env_type
  }
  
  return host.environment_name || '-'
}

// 获取描述预览（统一显示"点击查看"）
const getDescriptionPreview = (description) => {
  // 统一显示"点击查看"，在对话框中查看完整内容
  return '点击查看'
}

// 显示描述详情对话框
const showDescriptionDetail = (host) => {
  currentHost.value = host
  showDescriptionModal.value = true
}

// 从详情对话框编辑主机
const editHostFromDetail = () => {
  showDescriptionModal.value = false
  editHost(currentHost.value)
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'online': '在线',
    'offline': '离线'
  }
  return statusMap[status] || status
}

// 获取状态样式类
const getStatusClass = (status) => {
  return status === 'online' ? 'badge-online' : 'badge-offline'
}

// 批量操作相关函数
const isHostSelected = (hostId) => {
  return selectedHosts.value.includes(hostId)
}

const toggleHostSelection = (hostId) => {
  const index = selectedHosts.value.indexOf(hostId)
  if (index > -1) {
    selectedHosts.value.splice(index, 1)
  } else {
    selectedHosts.value.push(hostId)
  }
}

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedHosts.value = []
  } else {
    selectedHosts.value = filteredHosts.value.map(h => h.id)
  }
}

const clearSelection = () => {
  selectedHosts.value = []
}

// 同步所有主机状态并采集系统信息
const syncAllHosts = async () => {
  isSyncing.value = true
  try {
    // 1. 调用SSH连接检测API，同步主机状态
    const result = await api.syncHostsStatus()
    console.log('主机状态同步成功:', result)
    
    // 2. 重新获取主机列表（获取更新后的状态）
    await fetchHosts()
    
    // 3. 对所有在线主机采集系统信息（后台执行，不阻塞）
    const onlineHosts = hosts.value.filter(h => h.status === 'online')
    if (onlineHosts.length > 0) {
      console.log(`开始采集 ${onlineHosts.length} 台在线主机的系统信息...`)
      
      // 并发采集，但限制并发数
      const collectPromises = onlineHosts.map(async (host, index) => {
        try {
          // 添加延迟避免同时发起太多请求
          await new Promise(resolve => setTimeout(resolve, index * 500))
          await api.collectSystemInfo(host.id)
          console.log(`✅ ${host.name} 系统信息采集成功`)
        } catch (error) {
          console.warn(`⚠️ ${host.name} 系统信息采集失败:`, error.message)
        }
      })
      
      // 不等待采集完成，让它在后台运行
      Promise.all(collectPromises).then(() => {
        console.log('所有主机系统信息采集完成')
        // 采集完成后刷新列表
        fetchHosts()
      })
    }
    
    // 同步结果已在页面上显示，不需要弹窗
    console.log(`同步完成: ${result.message}, 在线: ${result.online_count}, 离线: ${result.offline_count}`)
    
  } catch (error) {
    console.error('同步失败:', error)
  } finally {
    setTimeout(() => {
      isSyncing.value = false
    }, 500)
  }
}

// 单个主机关机/重启
const toggleHostPower = async (host) => {
  // 只处理在线主机的关机和重启操作
  if (host.status !== 'online') {
    alert('⚠️ 只能对在线主机进行关机或重启操作')
    return
  }
  
  const action = confirm('选择操作:\n确定 = 关机\n取消 = 重启\n\n注意: 关机操作将在1分钟后执行')
  if (action === null) return // 用户取消
  
  const actionType = action ? 'shutdown' : 'reboot'
  const actionText = action ? '关机' : '重启'
  
  try {
    const result = await api.hostPowerAction(host.id, actionType)
    alert(`✅ ${result.message}\n\n${result.note}`)
    
    // 等待2秒后刷新主机列表
    setTimeout(async () => {
      await fetchHosts()
    }, 2000)
  } catch (error) {
    console.error(`${actionText}失败:`, error)
    const errorMsg = error.response?.data?.error || error.message
    alert(`❌ ${actionText}失败: ${errorMsg}`)
  }
}

// 批量关机主机
const bulkStopHosts = async () => {
  // 只关机在线的主机
  const onlineHosts = selectedHosts.value.filter(hostId => {
    const host = hosts.value.find(h => h.id === hostId)
    return host && host.status === 'online'
  })
  
  if (onlineHosts.length === 0) {
    alert('⚠️ 没有选中在线的主机')
    return
  }
  
  if (!confirm(`确定要关机选中的 ${onlineHosts.length} 台在线主机吗？\n\n注意: 关机操作将在1分钟后执行`)) return
  
  try {
    const promises = onlineHosts.map(hostId => {
      return api.hostPowerAction(hostId, 'shutdown')
    })
    
    await Promise.all(promises)
    await fetchHosts()
    clearSelection()
    alert(`✅ 已向 ${onlineHosts.length} 台主机发送关机命令`)
  } catch (error) {
    console.error('批量关机失败:', error)
    alert('批量关机失败: ' + (error.response?.data?.detail || error.message))
  }
}

// 自动同步控制
const toggleAutoSync = () => {
  if (autoSyncEnabled.value) {
    startAutoSync()
  } else {
    stopAutoSync()
  }
}

const startAutoSync = () => {
  stopAutoSync() // 先清除旧的定时器
  syncTimer = setInterval(() => {
    syncAllHosts()
  }, syncInterval.value * 1000)
  console.log(`自动同步已启动，间隔: ${syncInterval.value}秒`)
}

const stopAutoSync = () => {
  if (syncTimer) {
    clearInterval(syncTimer)
    syncTimer = null
    console.log('自动同步已停止')
  }
}

const updateSyncInterval = () => {
  if (autoSyncEnabled.value) {
    startAutoSync()
  }
}

// 导出Excel功能
const exportToExcel = () => {
  try {
    // 准备导出数据
    const exportData = hosts.value.map(host => {
      return {
        '主机名': host.name,
        'IP地址': host.ip,
        '端口': host.port,
        '用户名': host.username,
        '认证方式': host.auth_type === 'password' ? '密码' : '密钥',
        '状态': getStatusText(host.status),
        '项目': host.project_name || '-',
        '环境类型': getHostEnvTypeName(host),
        '主机组': host.host_group_name || '-',
        '描述': host.description || '-',
        '创建时间': host.created_at ? new Date(host.created_at).toLocaleString('zh-CN') : '-'
      }
    })

    // 创建工作簿
    const worksheet = XLSX.utils.json_to_sheet(exportData)
    const workbook = XLSX.utils.book_new()
    XLSX.utils.book_append_sheet(workbook, worksheet, '主机列表')

    // 设置列宽
    const colWidths = [
      { wch: 20 }, // 主机名
      { wch: 15 }, // IP地址
      { wch: 8 },  // 端口
      { wch: 12 }, // 用户名
      { wch: 10 }, // 认证方式
      { wch: 8 },  // 状态
      { wch: 15 }, // 项目
      { wch: 12 }, // 环境类型
      { wch: 15 }, // 主机组
      { wch: 30 }, // 描述
      { wch: 20 }  // 创建时间
    ]
    worksheet['!cols'] = colWidths

    // 生成文件名（包含时间戳）
    const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
    const fileName = `主机列表_${timestamp}.xlsx`

    // 导出文件
    XLSX.writeFile(workbook, fileName)
    
    alert(`成功导出 ${hosts.value.length} 条主机记录！\n文件已保存到下载文件夹: ${fileName}`)
  } catch (error) {
    console.error('导出Excel失败:', error)
    alert('导出失败: ' + error.message)
  }
}

// 组件卸载时清理定时器
onBeforeUnmount(() => {
  stopAutoSync()
})

// 计算内存使用百分比
const getMemoryPercent = (host) => {
  if (!host.memory_total || !host.memory_used) return 0
  return Math.round((host.memory_used / host.memory_total) * 100)
}

// 获取内存显示文本
const getMemoryText = (host) => {
  const percent = getMemoryPercent(host)
  const usedGB = (host.memory_used / 1024).toFixed(1)
  const totalGB = (host.memory_total / 1024).toFixed(1)
  return `${usedGB}/${totalGB}GB (${percent}%)`
}

// 计算磁盘使用百分比
const getDiskPercent = (host) => {
  if (!host.disk_total || !host.disk_used) return 0
  return Math.round((host.disk_used / host.disk_total) * 100)
}

// 获取磁盘显示文本
const getDiskText = (host) => {
  const percent = getDiskPercent(host)
  return `${host.disk_used}/${host.disk_total}GB (${percent}%)`
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  formData.value = {
    name: '',
    ip: '',
    mac_address: '',
    port: 22,
    username: '',
    auth_type: 'password',
    password: '',
    ssh_key: '',
    project: '',
    environment: '',
    host_group: '',
    description: ''
  }
}
</script>

<style scoped>
/* Header Wrapper */
.card-header-wrapper {
  background: linear-gradient(135deg, rgba(255, 70, 85, 0.05), rgba(0, 255, 200, 0.05));
  border-bottom: 2px solid var(--color-border);
}

.card-header {
  padding: 16px 20px;
}

.header-title {
  display: flex;
  align-items: center;
}

.title-text {
  font-size: 20px;
  font-weight: 700;
  color: var(--color-accent-cyan);
  text-transform: uppercase;
  letter-spacing: 2px;
}

/* Header Actions */
.header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

/* Action Buttons */
.btn-action {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  font-size: 14px;
  font-weight: 600;
  border: 2px solid;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.05);
  color: #fff;
  text-transform: none;
  letter-spacing: 0.5px;
}

.btn-action:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3);
}

.btn-action:active {
  transform: translateY(0);
}

.btn-icon {
  font-size: 16px;
  line-height: 1;
}

.btn-text {
  font-size: 13px;
}

/* Export Button */
.btn-export {
  background: linear-gradient(135deg, #4caf50, #66bb6a);
  border-color: #4caf50;
}

.btn-export:hover {
  background: linear-gradient(135deg, #388e3c, #4caf50);
  border-color: #388e3c;
}

/* Sync Button */
.btn-sync {
  background: linear-gradient(135deg, #2196f3, #42a5f5);
  border-color: #2196f3;
}

.btn-sync:hover {
  background: linear-gradient(135deg, #1976d2, #2196f3);
  border-color: #1976d2;
}

.sync-icon {
  display: inline-block;
  font-size: 16px;
  transition: transform 0.3s;
  line-height: 1;
}

.sync-icon.syncing {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* Add Button */
.btn-add {
  background: linear-gradient(135deg, #ff4655, #ff7b85);
  border-color: #ff4655;
}

.btn-add:hover {
  background: linear-gradient(135deg, #e63946, #ff4655);
  border-color: #e63946;
}

.btn-add .btn-icon {
  font-size: 18px;
  font-weight: bold;
}

/* Sync Controls Group */
.sync-controls-group {
  display: inline-flex;
  align-items: center;
  gap: 10px;
  padding: 8px 16px;
  background: rgba(0, 0, 0, 0.3);
  border: 2px solid rgba(255, 70, 85, 0.4);
  border-radius: 6px;
  min-height: 42px;
}

/* Bulk Actions Bar */
.bulk-actions-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 20px;
  background: linear-gradient(135deg, rgba(255, 70, 85, 0.1), rgba(255, 123, 133, 0.1));
  border-bottom: 2px solid var(--color-accent-red);
}

.selected-count {
  color: var(--color-accent-cyan);
  font-weight: 600;
  font-size: 14px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.btn-success {
  background: linear-gradient(135deg, #4caf50, #66bb6a);
  border-color: #4caf50;
}

.btn-success:hover {
  background: linear-gradient(135deg, #388e3c, #4caf50);
}

.btn-secondary {
  background: linear-gradient(135deg, #757575, #9e9e9e);
  border-color: #757575;
}

.btn-secondary:hover {
  background: linear-gradient(135deg, #616161, #757575);
}

/* Inline Sync Controls */
.sync-toggle-inline {
  display: inline-flex;
  align-items: center;
  gap: 6px;
  cursor: pointer;
  color: #fff;
  font-size: 13px;
  padding: 0;
  background: transparent;
  border: none;
  transition: all 0.3s;
}

.sync-toggle-inline:hover .toggle-text {
  color: var(--color-accent-cyan);
}

.sync-toggle-inline input[type="checkbox"] {
  width: 20px;
  height: 20px;
  margin: 0;
  cursor: pointer;
  accent-color: var(--color-accent-cyan);
}

.toggle-text {
  font-size: 13px;
  font-weight: 600;
  transition: color 0.3s;
  white-space: nowrap;
}

.sync-interval-select-inline {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(255, 70, 85, 0.5);
  border-radius: 4px;
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  min-width: 70px;
  height: 32px;
  line-height: 1;
  transition: all 0.3s;
}

.sync-interval-select-inline:hover {
  background: rgba(255, 255, 255, 0.95);
  color: #000;
  border-color: var(--color-accent-cyan);
}

.sync-interval-select-inline:focus {
  outline: none;
  border-color: var(--color-accent-cyan);
  background: rgba(255, 255, 255, 0.95);
  color: #000;
  box-shadow: 0 0 0 2px rgba(0, 255, 200, 0.2);
}

.sync-interval-select-inline option {
  background: #1a1a2e;
  color: #fff;
  padding: 8px;
}

.sync-indicator-inline {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.1);
  border: 1px solid rgba(158, 158, 158, 0.5);
  border-radius: 4px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 16px;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 36px;
  height: 32px;
  transition: all 0.3s;
}

.sync-indicator-inline.active {
  border-color: var(--color-accent-cyan);
  background: rgba(0, 255, 200, 0.2);
  color: var(--color-accent-cyan);
  box-shadow: 0 0 12px rgba(0, 255, 200, 0.4);
}

.sync-indicator-inline .triangle {
  display: inline-block;
  font-size: 14px;
  line-height: 1;
}

.sync-indicator-inline.active .triangle {
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0.3; }
}

/* Selected Row */
.selected-row {
  background: rgba(255, 70, 85, 0.1) !important;
}

.search-input {
  max-width: 400px;
}

.terminals-section {
  display: grid;
  gap: 20px;
}

.terminal-wrapper {
  width: 100%;
}

.btn-sm {
  padding: 8px 12px;
  font-size: 14px;
  min-width: 40px;
}

.modal-sm {
  max-width: 500px;
}

/* Modal Styles */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: var(--color-bg-secondary);
  border: 2px solid var(--color-accent-cyan);
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 2px solid var(--color-border);
}

.modal-header h2 {
  color: var(--color-accent-cyan);
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 18px;
}

.modal-close {
  background: transparent;
  border: none;
  color: var(--color-accent-red);
  font-size: 24px;
  cursor: pointer;
}

.modal-body {
  padding: 20px;
}

.form-section {
  background: rgba(0, 255, 200, 0.05);
  border: 1px solid rgba(0, 255, 200, 0.2);
  border-radius: 8px;
  padding: 15px;
  margin: 15px 0;
}

.form-section h4 {
  margin: 0 0 15px 0;
  font-size: 14px;
  font-weight: 600;
  letter-spacing: 1px;
}

/* 测试SSH按钮 */
.btn-test-ssh {
  background: linear-gradient(135deg, #2196f3, #42a5f5);
  border: 2px solid #2196f3;
  color: white;
  padding: 12px 24px;
  font-size: 14px;
  font-weight: 600;
  white-space: nowrap;
  width: 100%;
  transition: all 0.3s;
}

.btn-test-ssh:hover:not(:disabled) {
  background: linear-gradient(135deg, #1976d2, #2196f3);
  border-color: #1976d2;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(33, 150, 243, 0.4);
}

.btn-test-ssh:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 自动获取MAC按钮 */
.btn-auto-get {
  background: linear-gradient(135deg, #4caf50, #66bb6a);
  border: 2px solid #4caf50;
  color: white;
  padding: 8px 16px !important;
  font-size: 12px !important;
  white-space: nowrap;
  min-width: 110px;
  height: 42px;
  transition: all 0.3s;
}

.btn-auto-get:hover:not(:disabled) {
  background: linear-gradient(135deg, #388e3c, #4caf50);
  border-color: #388e3c;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(76, 175, 80, 0.4);
}

.btn-auto-get:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 系统信息样式 */
.os-type-badge {
  display: inline-block;
  padding: 4px 10px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
  white-space: nowrap;
}

.os-type-badge.no-data {
  background: rgba(139, 154, 170, 0.3);
  color: var(--color-text-secondary);
}

.text-small {
  font-size: 12px;
  color: var(--color-text-secondary);
}

.cpu-info, .memory-info, .disk-info {
  font-family: monospace;
  font-size: 12px;
  color: var(--color-text-primary);
  font-weight: 600;
}

.arch-badge {
  display: inline-block;
  padding: 3px 8px;
  background: rgba(33, 150, 243, 0.2);
  color: #64b5f6;
  border-radius: 8px;
  font-size: 11px;
  font-weight: 600;
  font-family: monospace;
}

.ip-badge {
  display: inline-block;
  padding: 4px 10px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: 600;
  font-family: monospace;
  white-space: nowrap;
}

.ip-badge.public {
  background: rgba(76, 175, 80, 0.2);
  color: #81c784;
  border: 1px solid rgba(76, 175, 80, 0.3);
}

.ip-badge.private {
  background: rgba(255, 152, 0, 0.2);
  color: #ffb74d;
  border: 1px solid rgba(255, 152, 0, 0.3);
}

/* 表格容器 - 支持横向滚动 */
.table-wrapper {
  width: 100%;
  overflow-x: auto;
  overflow-y: visible;
  -webkit-overflow-scrolling: touch;
  margin-bottom: 20px;
  position: relative;
}

/* 滚动提示 */
.scroll-hint {
  text-align: center;
  padding: 8px;
  background: linear-gradient(135deg, rgba(255, 70, 85, 0.1) 0%, rgba(255, 123, 138, 0.1) 100%);
  color: var(--color-accent-red);
  font-size: 12px;
  font-weight: 600;
  border-radius: 8px 8px 0 0;
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 0.6; }
  50% { opacity: 1; }
}

/* 自定义滚动条样式 */
.table-wrapper::-webkit-scrollbar {
  height: 12px;
}

.table-wrapper::-webkit-scrollbar-track {
  background: var(--color-bg-secondary);
  border-radius: 6px;
}

.table-wrapper::-webkit-scrollbar-thumb {
  background: linear-gradient(135deg, #ff4655 0%, #ff7b8a 100%);
  border-radius: 6px;
  transition: all 0.3s;
}

.table-wrapper::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(135deg, #ff7b8a 0%, #ff4655 100%);
}

/* 表格宽度调整 */
table {
  min-width: 1800px; /* 增加最小宽度以容纳更多列 */
}

table th, table td {
  white-space: nowrap;
  padding: 12px 8px;
  font-size: 12px;
}

/* 迷你采集按钮 */
.btn-collect-mini {
  display: inline-block;
  margin-left: 6px;
  padding: 2px 6px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  vertical-align: middle;
}

.btn-collect-mini:hover {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.4);
}

/* 描述预览样式 */
.description-preview {
  display: inline-block;
  max-width: 150px;
  padding: 4px 8px;
  background: linear-gradient(135deg, rgba(255, 70, 85, 0.1) 0%, rgba(255, 123, 138, 0.1) 100%);
  border: 1px solid rgba(255, 70, 85, 0.3);
  border-radius: 6px;
  color: var(--color-accent-red);
  font-size: 12px;
  cursor: pointer;
  transition: all 0.3s;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.description-preview:hover {
  background: linear-gradient(135deg, rgba(255, 70, 85, 0.2) 0%, rgba(255, 123, 138, 0.2) 100%);
  border-color: var(--color-accent-red);
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(255, 70, 85, 0.3);
}

/* 描述详情对话框样式 */
.description-detail {
  padding: 16px;
  background: var(--color-bg-secondary);
  border-radius: 8px;
}

.host-info-row {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.host-info-row .label {
  min-width: 100px;
  font-weight: 600;
  color: var(--color-accent-red);
}

.host-info-row .value {
  flex: 1;
  color: var(--color-text-primary);
}

.description-content {
  margin-top: 16px;
}

.description-content .label {
  font-weight: 600;
  color: var(--color-accent-red);
  margin-bottom: 8px;
}

.description-text {
  padding: 12px;
  background: rgba(0, 0, 0, 0.2);
  border-radius: 6px;
  color: var(--color-text-primary);
  line-height: 1.6;
  white-space: pre-wrap;
  word-wrap: break-word;
  max-height: 300px;
  overflow-y: auto;
}

.description-text:empty::before {
  content: '暂无描述信息';
  color: #888;
  font-style: italic;
}

.empty-description {
  color: #888 !important;
  font-style: italic;
  text-align: center;
}

/* 资源进度条样式 */
.resource-progress {
  display: flex;
  flex-direction: column;
  gap: 4px;
  min-width: 140px;
}

.progress-bar {
  width: 100%;
  height: 8px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  overflow: hidden;
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.progress-fill {
  height: 100%;
  transition: width 0.3s ease, background 0.3s ease;
  border-radius: 3px;
}

.progress-fill.memory {
  background: linear-gradient(90deg, #4caf50 0%, #8bc34a 50%, #ffeb3b 75%, #ff9800 90%, #f44336 100%);
}

.progress-fill.disk {
  background: linear-gradient(90deg, #2196f3 0%, #03a9f4 50%, #00bcd4 75%, #ff9800 90%, #f44336 100%);
}

.progress-text {
  font-size: 11px;
  color: var(--color-text-secondary);
  font-family: monospace;
  text-align: center;
  font-weight: 600;
}
</style>
